package com.example.final_project.service.impl;

import com.example.final_project.entity.Order;
import com.example.final_project.entity.OrderDetail;
import com.example.final_project.mapper.OrderMapper;
import com.example.final_project.mapper.OrderDetailMapper;
import com.example.final_project.service.InventoryService;
import com.example.final_project.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private InventoryService inventoryService;

    @Override
    @Transactional
    public boolean create(Order order, List<OrderDetail> orderDetails) {
        // 检查用户是否重复购买教材
        List<Long> purchasedBookIds = orderDetailMapper.findBookIdsByUserId(order.getUserId());
        for (OrderDetail newDetail : orderDetails) {
            if (purchasedBookIds.contains(newDetail.getBookId())) {
                throw new RuntimeException("用户已购买教材ID为 " + newDetail.getBookId() + " 的教材，每个教材对于每一个用户只能购买一个。");
            } else if (newDetail.getQuantity() > 1) {
                // 如果是新购买的教材，数量必须为1
                throw new RuntimeException("每个教材对于每一个用户只能购买一个，教材ID " + newDetail.getBookId() + " 的数量不能大于1。");
            }
        }

        // 生成订单编号
        order.setOrderNo(generateOrderNo());
        // 设置订单状态为待付款
        order.setStatus("PENDING");
        // 计算订单总金额
        BigDecimal totalAmount = BigDecimal.ZERO;

        // 遍历订单详情，计算总金额 (不再进行库存检查和扣除)
        for (OrderDetail detail : orderDetails) {
            totalAmount = totalAmount.add(detail.getPrice().multiply(new BigDecimal(detail.getQuantity())));
        }
        order.setTotalAmount(totalAmount);

        // 保存订单
        int result = orderMapper.insert(order);
        if (result > 0) {
            // 保存订单明细 (不再更新库存)
            for (OrderDetail detail : orderDetails) {
                detail.setOrderId(order.getId());
                List<OrderDetail> detailList = new ArrayList<>();
                detailList.add(detail);
                orderDetailMapper.batchInsert(detailList);
            }
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean updateStatus(Long id, String status) {
        // 获取原订单信息
        Order originalOrder = orderMapper.selectById(id);
        if (originalOrder == null) {
            return false; // 订单不存在
        }

        // 如果订单状态从非取消变为取消，则恢复库存
        if (!"CANCELLED".equals(originalOrder.getStatus()) && "CANCELLED".equals(status)) {
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
            if (orderDetails != null) {
                for (OrderDetail detail : orderDetails) {
                    inventoryService.addStock(detail.getBookId(), detail.getQuantity());
                }
            }
        } else if (!"PAID".equals(originalOrder.getStatus()) && "PAID".equals(status)) {
            // 如果订单状态从非已支付变为已支付，则扣除库存
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
            if (orderDetails != null) {
                for (OrderDetail detail : orderDetails) {
                    Integer stock = inventoryService.getStockByBookId(detail.getBookId());
                    if (stock == null || detail.getQuantity() > stock) {
                        throw new RuntimeException("图书库存不足，无法支付订单。书籍ID: " + detail.getBookId());
                    }
                    inventoryService.deductStock(detail.getBookId(), detail.getQuantity());
                }
            }
        }

        Order order = new Order();
        order.setId(id);
        order.setStatus(status);
        return orderMapper.update(order) > 0;
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        // 获取订单信息以检查状态
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return false; // 订单不存在
        }

        // 如果订单状态是待支付，则不允许删除
        if ("PENDING".equals(order.getStatus())) {
            throw new RuntimeException("待支付订单无法直接删除，请先取消或支付。");
        }

        // 不再在删除订单时恢复库存
        // List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        // if (orderDetails != null) {
        //     for (OrderDetail detail : orderDetails) {
        //         // 恢复库存
        //         inventoryService.addStock(detail.getBookId(), detail.getQuantity());
        //     }
        // }

        // 先删除订单明细
        orderDetailMapper.deleteByOrderId(id);
        // 再删除订单
        return orderMapper.deleteById(id) > 0;
    }

    @Override
    public Order getById(Long id) {
        return orderMapper.selectById(id);
    }

    @Override
    public PageInfo<Order> getList(String orderNo, Long userId, String status, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> list = orderMapper.selectList(orderNo, userId, status);
        return new PageInfo<>(list);
    }

    @Override
    public List<OrderDetail> getOrderDetailsByOrderId(Long orderId) {
        return orderDetailMapper.selectByOrderId(orderId);
    }

    @Override
    public int countAllOrders() {
        return orderMapper.countAllOrders();
    }

    @Override
    public List<Order> getLatestOrders(int limit) {
        return orderMapper.getLatestOrders(limit);
    }

    @Override
    public Map<String, Integer> getOrderStatusStats() {
        List<Map<String, Object>> list = orderMapper.getOrderStatusStats();
        Map<String, Integer> result = new HashMap<>();
        for (Map<String, Object> map : list) {
            String type = (String) map.get("type");
            Integer cnt = ((Number) map.get("cnt")).intValue();
            result.put(type, cnt);
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> getOrderTrend7Days() {
        return orderMapper.getOrderTrend7Days();
    }

    // 生成订单编号
    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis();
    }
} 